<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Article;
use Illuminate\Http\Request;
use Carbon\Carbon;
class ChatController extends Controller{

    /**
     * index  
     * 
     * @param Request $request 
     * @access public
     * @return void
     */
    public function index(Request $request){
        $user = $request->user();
        //获取持仓数据
        $messages = \App\Models\ChatMessage::where('created_at','>',Carbon::parse('-3 hour')->toDateTimeString())
                ->orderBy('id','desc')
                ->paginate(10);
        $messages = $messages->sortBy('id');
        return view('home.chat.im-chat',compact('user','messages'));
    }

    public function more(Request $request){
        $user = $request->user();
        //获取持仓数据
        $messages = \App\Models\ChatMessage::where('created_at','>',Carbon::parse('-3 hour')->toDateTimeString())
                ->orderBy('id','desc')
                ->paginate(10);
        $messages = $messages->sortBy('id');
        $new = [];
        foreach($messages as $k=>$m){
            if($m->user_id != $user->id){
                $arr['type'] = 'eui-chat-receiver';
            }else{
                $arr['type'] = 'eui-chat-sender';
            }
             
            //$arr['chatName'] = $m->user->name.'['.date('H:i:s',strtotime($m->created_at)).']'; 
            $arr['chatName'] = $m->user->name; 
            $arr['msg'] = $m->message;
            $new[] = $arr;
            
        }
        return response()->json($new);
        //return response()->json(['messages'=>$new]);
        //return view('home.chat.im-chat',compact('user','messages'));
    }

    public function sendChat(Request $request){
        $user = $request->user();
        if($user->gag){
            return;
        }
        $message = \App\Models\ChatMessage::create([
            'user_id' => $user->id,
            'message' => $this->characet(str_replace(array("\r\n", "\r", "\n"), "", htmlspecialchars($request->message)) )
        ]);

        event(new \App\Events\ChatMessageWasReceived($message, $user));
    }
	
    public function characet($data){
        if( !empty($data) ){
            $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
            if( $fileType != 'UTF-8'){
                $data = mb_convert_encoding($data ,'utf-8' , $fileType);
            }
        }
        return $data;
    }

}